#! /usr/local/bin/ruby

=begin

GroupsOfFiles is an intermediate data store. It's
used to post-process results from a duplicates run
and format them for output.

Input:
The constructor takes a hash of arrays of strings 
and eliminates singletons.

Output:
Convenience functions are provided to output the result in a variety of formats.
These include an array of arrays of strings and a text table.

=end

FileInGroup = Struct.new("FileInGroup", :groupnum,  :basename, :filesize, :path, :time)

class GroupsOfFiles
  attr_accessor :rep

  def initialize(hash)
    @rep = hash

    @rep.delete_if { | key, value |
      value.length <= 1
    }
  end

  def empty?
    @rep.empty?
  end

  def to_a
    @rep.values.collect { | a | a.sort }.sort
  end

  def to_s
    strings = to_a.collect { |arr| arr.join($/) << $/ }
    strings.join($/)
  end

  def to_table
    output = ""
    @rep.keys.each_with_index do |key, i|
      a = @rep[key]
      output << "#$/#{key}#$/-#$/"
      a.sort!
      a.each { |filepath|
        struct = GroupsOfFiles.make_FileInGroup(i+1, filepath)
        output << "#{struct.groupnum}\t#{struct.basename}\t#{struct.filesize}\t#{struct.time}\t#{struct.path}#$/"
      }
    end
    return output
  end

  def each(&block)
    @rep.each { |x| yield x }
  end
  
  def to_h    
    result = {}    
    @rep.each { |key, value| result[key.to_s] = value.sort }
    result
  end
  
  def GroupsOfFiles.make_FileInGroup(index, filepath)
    if FileTest.exists?(filepath)
      size = File.size(filepath)
      time = File.mtime(filepath)
    else
      size = 0
      time = "Wed Dec 31 19:00:00 EST 1969"
    end
  
    basename = File.basename(filepath)

    FileInGroup.new(index, basename, size, filepath, time)
  end
end
